package com.tubeonfire.model;

import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.tubeonfire.entity.SpecialTube;

public class SpecialTubeModel {

	private static Objectify ofy;

	private static Cache cache = null;

	private static boolean isRegisted = false;

	private static ObjectifyOpts opts = null;

	private static String cachePrefix = "SpecialTubeModel_";

	public static void init() {
		if (!isRegisted) {
			isRegisted = true;
			try {
				ObjectifyService.register(SpecialTube.class);
			} catch (Exception e) {
				isRegisted = false;
			}
			try {
				cache = CacheManager.getInstance().getCacheFactory()
						.createCache(Collections.emptyMap());
			} catch (CacheException e) {
				isRegisted = false;
			}
			opts = new ObjectifyOpts().setSessionCache(true);
		}
		ofy = ObjectifyService.begin(opts);
	}

	public SpecialTubeModel() {
		init();
	}

	@SuppressWarnings("unchecked")
	public static void insert(SpecialTube obj) {
		init();
		if (cache != null) {
			String prefix = cachePrefix + "id_" + obj.getId();
			cache.put(prefix, obj);
			cache.remove(cachePrefix + "type_" + obj.getType());
		}
		ofy.put(obj);
	}

	public static void delete(SpecialTube obj) {
		init();
		String prefix = cachePrefix + "id_" + obj.getId();
		if (cache != null && cache.containsKey(prefix)) {
			cache.remove(prefix);
			cache.remove(cachePrefix + "type_" + obj.getType());
		}
		ofy.delete(obj);
	}

	@SuppressWarnings("unchecked")
	public static SpecialTube byId(String id, boolean fromCache) {
		init();
		SpecialTube obj = new SpecialTube();
		String prefix = cachePrefix + "id_" + id;
		if (cache != null && cache.containsKey(prefix) && fromCache) {
			obj = (SpecialTube) cache.get(prefix);
		} else {
			try {
				obj = ofy.get(new Key<SpecialTube>(SpecialTube.class, id));
				if (fromCache) {
					cache.put(prefix, obj);
				}
			} catch (Exception e) {
				obj = null;
			}
		}
		return obj;
	}

	@SuppressWarnings("unchecked")
	public static SpecialTube getByType(String type, boolean fromCache) {
		init();
		SpecialTube obj = new SpecialTube();
		String prefix = cachePrefix + "type_" + type;
		if (cache != null && cache.containsKey(prefix) && fromCache) {
			obj = (SpecialTube) cache.get(prefix);
		} else {
			Query<SpecialTube> q = ofy.query(SpecialTube.class).filter("type",
					type);
			obj = q.get();
			if (obj != null && fromCache) {
				cache.put(prefix, obj);
			}
		}
		return obj;
	}
}
